<template>
  <Dialog :title="dialogTitle" v-model="dialogVisible">
    <el-form
      ref="formRef"
      :model="formData"
      :rules="formRules"
      label-width="100px"
      v-loading="formLoading"
    >
      <el-form-item label="菜谱名称" prop="recipeName">
        <el-input v-model="formData.recipeName" placeholder="请输入菜谱名称" />
      </el-form-item>
      <el-form-item label="菜谱分类" prop="recipeTypeId">
        <el-select v-model="formData.recipeTypeId" placeholder="请选择菜谱分类" class="w-full">
          <el-option
            v-for="item in recipeTypeList"
            :key="item.id"
            :label="item.typeName"
            :value="item.typeId"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="食材" prop="foods" class="mt-32px">
        <el-table :data="foodList" class="-mt-10px">
          <el-table-column label="食材" min-width="180" label-class-name="!text-center">
            <template #default="{ row }">
              <el-cascader
                v-model="row.foodValue"
                :options="foodTypeList"
                :props="foodCascaderProps"
                clearable
                filterable
                placeholder="请选择食材"
                class="w-full"
              />
            </template>
          </el-table-column>
          <el-table-column label="用量(克)" min-width="120" label-class-name="!text-center">
            <template #default="{ row }">
              <el-input-number
                v-model="row.usage"
                :min="0"
                :step="1"
                placeholder="请输入用量克重"
                class="!w-100%"
              />
            </template>
          </el-table-column>
          <el-table-column align="center" label="操作" width="60" label-class-name="!text-center">
            <template #default="{ $index }">
              <el-button @click="handleDeleteFood($index)" link>—</el-button>
            </template>
          </el-table-column>
        </el-table>
        <div class="flex justify-end mt-3 w-full">
          <el-button @click="handleAddFood" round>+ 添加食材</el-button>
        </div>
      </el-form-item>
      <el-form-item label="描述" prop="description">
        <el-input
          v-model="formData.description"
          type="textarea"
          placeholder="请输入菜谱描述，比如做法等"
        />
      </el-form-item>
      <el-form-item label="排序" prop="sort">
        <el-input-number
          v-model="formData.sort"
          :min="0"
          placeholder="请输入排序号"
          clearable
          controls-position="right"
          class="!w-1/1"
        />
      </el-form-item>
      <el-form-item label="状态" prop="status">
        <el-radio-group v-model="formData.status">
          <el-radio
            v-for="dict in getIntDictOptions(DICT_TYPE.COMMON_STATUS)"
            :key="dict.value"
            :label="dict.value"
          >
            {{ dict.label }}
          </el-radio>
        </el-radio-group>
      </el-form-item>
    </el-form>
    <template #footer>
      <el-button @click="submitForm" type="primary" :disabled="formLoading">确 定</el-button>
      <el-button @click="dialogVisible = false">取 消</el-button>
    </template>
  </Dialog>
</template>
<script setup lang="ts">
import { getIntDictOptions, DICT_TYPE } from '@/utils/dict'
import { RecipesApi, Recipes } from '@/api/school/recipe/recipes'
import { RecipesTypeApi, RecipesType } from '@/api/school/recipe/recipeType'
import { RecipeFoodTypeApi } from '@/api/school/recipe/foodType'
import { RecipeFoodApi } from '@/api/school/recipe/food'
import { defaultProps } from '@/utils/tree'

/** 菜谱 表单 */
defineOptions({ name: 'RecipesForm' })

const { t } = useI18n() // 国际化
const message = useMessage() // 消息弹窗

const dialogVisible = ref(false) // 弹窗的是否展示
const dialogTitle = ref('') // 弹窗的标题
const formLoading = ref(false) // 表单的加载中：1）修改时的数据加载；2）提交的按钮禁用
const formType = ref('') // 表单的类型：create - 新增；update - 修改
const formData = ref({
  id: undefined,
  recipeId: undefined,
  recipeName: undefined,
  recipeTypeId: undefined,
  foods: undefined,
  description: undefined,
  sort: 0,
  status: 0
})
const formRules = reactive({
  recipeName: [{ required: true, message: '菜谱名称不能为空', trigger: 'blur' }],
  recipeTypeId: [{ required: true, message: '菜谱分类不能为空', trigger: 'blur' }],
  sort: [{ required: true, message: '排序不能为空', trigger: 'blur' }],
  status: [{ required: true, message: '状态不能为空', trigger: 'blur' }]
})
const formRef = ref() // 表单 Ref

// 菜谱分类列表
const recipeTypeList = ref<RecipesType[]>([])

// 食物相关
const foodTypeList = ref([]) // 食物分类列表
const foodList: any = ref([]) // 食物列表

// 食物级联选择器属性
const foodCascaderProps: any = {
  ...defaultProps,
  multiple: false,
  lazy: true,
  emitPath: true,
  lazyLoad: async (node, resolve) => {
    const { level, data } = node
    // 二级节点（食物）需要懒加载
    if (level === 1) {
      try {
        const list = await RecipeFoodApi.getRecipeFoodList(data.sid)
        list.forEach((item) => {
          item.id = item.foodId
          item.name = item.foodName
          item.leaf = true
        })
        resolve(list)
      } catch (e) {
        console.error(e)
        resolve([])
      }
    } else {
      resolve([])
    }
  }
}

// 添加食材
const handleAddFood = () => {
  foodList.value.push({
    foodValue: undefined,
    usage: 0
  })
}

// 删除食材
const handleDeleteFood = (index) => {
  foodList.value.splice(index, 1)
}

// 获取菜谱分类列表
const getRecipeTypeList = async () => {
  try {
    recipeTypeList.value = await RecipesTypeApi.getRecipesTypeSimpleList()
  } catch (err) {
    console.error(err)
  }
}

// 获取食物分类列表
const getFoodTypeList = async () => {
  try {
    const list = await RecipeFoodTypeApi.getSimpleRecipeFoodType()
    list.forEach((item) => {
      item.id = item.sid
    })
    foodTypeList.value = list
  } catch (err) {
    console.error(err)
  }
}

/** 打开弹窗 */
const open = async (type: string, id?: number) => {
  dialogVisible.value = true
  dialogTitle.value = t('action.' + type)
  formType.value = type
  resetForm()

  // 获取下拉列表数据
  await Promise.all([getRecipeTypeList(), getFoodTypeList()])

  // 修改时，设置数据
  if (id) {
    formLoading.value = true
    try {
      const res = await RecipesApi.getRecipes(id)
      formData.value = res
      // 解析foods字段
      if (res?.foodList?.length) {
        try {
          // 转换为表格数据格式
          foodList.value = res?.foodList.map((item) => ({
            foodValue: [item.foodTypeId, item.foodId],
            usage: item.usage
          }))
        } catch (e) {
          console.error('解析foods字段失败', e)
          foodList.value = []
        }
      }
    } finally {
      formLoading.value = false
    }
  }
}
defineExpose({ open }) // 提供 open 方法，用于打开弹窗

/** 提交表单 */
const emit = defineEmits(['success']) // 定义 success 事件，用于操作成功后的回调
const submitForm = async () => {
  // 校验表单
  await formRef.value.validate()
  // 提交请求
  formLoading.value = true
  try {
    // 处理foods字段为JSON字符串
    const foods = {}
    foodList.value.forEach((item) => {
      console.log(item, '---item')
      const foodId = item.foodValue[1]
      if (foodId) {
        foods[foodId] = item.usage
      }
    })

    const data = {
      ...formData.value,
      foods: JSON.stringify(foods)
    } as unknown as Recipes

    if (formType.value === 'create') {
      await RecipesApi.createRecipes(data)
      message.success(t('common.createSuccess'))
    } else {
      await RecipesApi.updateRecipes(data)
      message.success(t('common.updateSuccess'))
    }
    dialogVisible.value = false
    // 发送操作成功的事件
    emit('success')
  } finally {
    formLoading.value = false
  }
}

/** 重置表单 */
const resetForm = () => {
  formData.value = {
    id: undefined,
    recipeId: undefined,
    recipeName: undefined,
    recipeTypeId: undefined,
    foods: undefined,
    description: undefined,
    sort: 0,
    status: 0
  }
  foodList.value = []
  handleAddFood()
  formRef.value?.resetFields()
}
</script>
